package handConsistentHash;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 03010570
 * @date 2020/07/08
 * describe:
 */
public class ConsistentHashTest2 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        //initialize 4 service node
        PNode node1 = new PNode("IDC1", "192.0.0.1", 8080);
        PNode node2 = new PNode("IDC2", "172.0.0.2", 8081);
        PNode node3 = new PNode("IDC3", "127.0.2.3", 8082);
        PNode node4 = new PNode("IDC4", "192.168.0.4", 8083);
        PNode node5 = new PNode("IDC5", "127.0.1.2", 8084);
        PNode node6 = new PNode("IDC6", "172.0.12.2", 8085);
        PNode node7 = new PNode("IDC7", "168.0.10.3", 8086);
        PNode node8 = new PNode("IDC8", "127.0.0.4", 8087);
        PNode node9 = new PNode("IDC9", "192.0.120.1", 8088);
        PNode node10 = new PNode("IDC10", "196.0.20.2", 8089);

        List<PNode> pNodes = Arrays.asList(node1, node2, node3, node4, node5, node6, node7, node8, node9, node10);
        //hash them to hash ring
        int vNodeCount = 10;
        ConsistentHashAlgorithm consistentHashRouter = new ConsistentHashAlgorithm(pNodes, vNodeCount);//10 virtual node
        System.out.println("虚拟节点数量：" + vNodeCount);

        SortedMap<String, Integer> map = new TreeMap<>();
        for (PNode node : pNodes) {
            map.put(node.toString(), 0);
        }
        int count = 1000000;
        for (int i = 0; i < count; i++) {
            String randomIp = IPUtils.getRandomIp();
            PNode node = consistentHashRouter.getNode(randomIp);
            Integer aLong = map.get(node.toString());
            map.put(node.toString(), (aLong + 1));
        }
        long end = System.currentTimeMillis();
        ArrayList<Integer> list = new ArrayList<>();
        System.out.println("执行时间：" + (end - start) + " ms");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " ------ " + entry.getValue());
            list.add(entry.getValue());
        }

        double result = 0;
        for (Integer integer : list) {
            result += (integer - count / 10) * (integer - count / 10);
        }
        System.out.println("标准差："+Math.sqrt(result / 10));


//        goRoute(consistentHashRouter, requestIP1, requestIP2, requestIP3, requestIP4, requestIP5);

    }

    private static void goRoute(ConsistentHashAlgorithm consistentHashRouter, String... requestIps) {
        for (String requestIp : requestIps) {
            System.out.println(requestIp + " is route to " + consistentHashRouter.getNode(requestIp));
        }
    }


}
